package com.baiduspring.web.user;

import com.baiduspring.dao.entity.User;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.service.user.UserDetailsService;
import com.baiduspring.utils.ResponseResult;
import com.baiduspring.utils.SystemCode;
import com.baiduspring.vo.UserDetailsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
@Scope("prototype")
@RequestMapping("/user_details")
@Slf4j
public class UserDetailsController {
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 用户注册
     *
     * @param vo 参数
     * @return 返回注册结果
     */
    @PostMapping("/personal_profile")
    public ResponseResult<UserDetailsVO> register(UserDetailsVO vo, HttpServletRequest request) {
        ResponseResult<UserDetailsVO> result = new ResponseResult<>();
        result.setCode(SystemCode.SUCCESS);
        result.setMessage("操作成功");
        result.setData(vo);

        Object o = request.getSession().getAttribute("user");
        if (Objects.isNull(o)) {
            result.setMessage("登录已经失效，请重新登录...");
            return result;
        }

        User user = (User) o;
        vo.setAccount(user.getAccount());

        try {
            userDetailsService.merge(vo);
        } catch (BaiduSpringException e) {
            result.setCode(SystemCode.FAIL);
            result.setMessage(e.getErrorMsg());
        }

        return result;
    }

}
